﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;

namespace IFD2
{
    public partial class AircraftSeatMap : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Session["ACL"].ToString().IndexOf("ND1") < 0)
                {
                    Response.Redirect("unauthorized.aspx");
                }

                if (Request.QueryString["tail_no"] != null)
                    lblTailNo.Text = Request.QueryString["tail_no"].ToString();
                else
                    lblError.Text = "Bad page call!";

                lbtnQuery_Click(sender, e);
            }
            btnDelete.Attributes.Add("onclick", "javascript:return confirm('Are you sure?');");
            btnCopy.Attributes.Add("onclick", "javascript:return confirm('Are you sure?');");
            btnClear.Attributes.Add("onclick", "javascript:return confirm('Are you sure?');");
            ScriptManager1.RegisterPostBackControl(btnAdd);
            ScriptManager1.RegisterPostBackControl(btnChange);
        }

        protected void lbtnQuery_Click(object sender, EventArgs e)
        {
            int ret_code;
            int curr_x;
            SqlCommand cmd = new SqlCommand();
            //lblError.Text = "";

            //int max_x, max_y;
            //cmd.CommandText = "bll_aircraft_get_seat_map_dimension";
            //SqlParameter para = cmd.Parameters.AddWithValue("@tail_no", lblTailNo.Text);
            //para = cmd.Parameters.Add("@x", SqlDbType.TinyInt);
            //para.Direction = ParameterDirection.Output;
            //SqlParameter para2 = cmd.Parameters.Add("@y", SqlDbType.TinyInt);
            //para2.Direction = ParameterDirection.Output;

            //ret_code = TinyDAL.Exec(ref cmd);
            //if (ret_code != 0)
            //{
            //    lblError.Text = "Aircraft not found!";
            //    return;
            //}
            //max_x = Convert.ToInt16(para.Value);
            //max_y = Convert.ToInt16(para2.Value);

            DataTable dtMap = new DataTable();
            cmd.Parameters.Clear();
            cmd.CommandText = "bll_aircraft_get_seat_map";
            SqlParameter para = cmd.Parameters.AddWithValue("@tail_no", lblTailNo.Text);
            try
            {
                ret_code = TinyDAL.Exec(ref cmd, ref dtMap);
                switch (ret_code)
                {
                    case 0:
                        //lblError.Text = "OK.";
                        break;
                    case 1:
                        lblError.Text = "Aircraft not found!";
                        return;
                    default:
                        lblError.Text = "Error " + ret_code.ToString() + "! Contact system adminstartor!";
                        return;
                }

                tabSeatMap.Rows.Clear();
                TableRow tempRow = new TableRow();
                TableCell tempCell;
                int last_col = -1;// max_y;
                curr_x = 1;
                //tempCell = new TableCell();
                //tempCell.Text = "<b>"+max_y.ToString()+"</b>";
                //tempCell.HorizontalAlign = HorizontalAlign.Center;
                //tempRow.Cells.Add(tempCell);
                foreach (DataRow row in dtMap.Rows)
                {
                    if (last_col != Convert.ToInt16(row["y"])/* || last_col == max_y + 1*/)
                    {
                        tabSeatMap.Rows.Add(tempRow);
                        if (last_col - 1 != Convert.ToInt16(row["y"]))
                        {
                            for (last_col--; last_col > Convert.ToInt16(row["y"]); last_col--)
                            {
                                tempRow = new TableRow();
                                tempCell = new TableCell();
                                //tempCell.Width = 100;
                                tempCell.HorizontalAlign = HorizontalAlign.Center;
                                tempCell.Text = "<b>" + last_col.ToString() + "</b>";
                                tempRow.Cells.Add(tempCell);
                                tabSeatMap.Rows.Add(tempRow);
                            }
                        }

                        tempRow = new TableRow();
                        last_col = Convert.ToInt16(row["y"]);
                        tempCell = new TableCell();
                        //tempCell.Width = 100;
                        tempCell.Text = "<b>" + last_col.ToString() + "</b>";
                        tempCell.HorizontalAlign = HorizontalAlign.Center;
                        tempRow.Cells.Add(tempCell);

                        curr_x = 1;
                    }

                    //if (last_col == max_y + 1)
                    //{
                    //    last_col = Convert.ToInt16(row["y"]);
                    //}

                    if (curr_x != Convert.ToInt16(row["x"]))
                    {
                        for (; curr_x < Convert.ToInt16(row["x"]); curr_x++)
                        {
                            tempCell = new TableCell();
                            //tempCell.Width = 100;
                            tempCell.Text = "&nbsp;";
                            tempRow.Cells.Add(tempCell);
                        }
                    }

                    tempCell = new TableCell();
                    //tempCell.Width = 100;
                    if (row["cell_type"].ToString() == "S")
                        tempCell.Text = "&nbsp;<input name='CELL' type='radio' value='" + row["x"].ToString() + "|" + row["y"].ToString() + "'>" + row["row"].ToString() + row["col"].ToString() + "|" + row["load_area"].ToString() + "|" + row["cabin"].ToString() + "|" + row["class"].ToString().TrimEnd() + "|" + row["seat_type"].ToString().TrimEnd() + "|" + row["attributes"].ToString().TrimEnd() + "</input>";
                    else
                        tempCell.Text = "&nbsp;<input name='CELL' type='radio' value='" + row["x"].ToString() + "|" + row["y"].ToString() + "'>" + "=</input>";// row["cabin"].ToString();
                    tempRow.Cells.Add(tempCell);
                    curr_x = Convert.ToInt16(row["x"]) + 1;
                    //if (Convert.ToInt32(row["x"]) > max_x)
                    //    max_x = Convert.ToInt32(row["x"]);
                }
                dtMap.Clear();
                tabSeatMap.Rows.Add(tempRow);

                tempRow = new TableRow();
                tempCell = new TableCell();
                //tempCell.Width = 100;
                tempCell.Text = "<b>Y/X&nbsp;</b>";
                tempRow.Cells.Add(tempCell);
                for (ret_code = 1; ret_code <= curr_x - 1; ret_code++)
                {
                    tempCell = new TableCell();
                    //tempCell.Width = 150;
                    tempCell.Text = "&nbsp;<b>" + ret_code.ToString() + "</b>";
                    //tempCell.HorizontalAlign = HorizontalAlign.Center;
                    tempRow.Cells.Add(tempCell);
                }
                tabSeatMap.Rows.Add(tempRow);
                tempRow = new TableRow();
            }
            catch (Exception ex)
            {
                if (Application["DEBUG"].ToString() == "1")
                    lblError.Text = ex.Message;
                else
                    lblError.Text = "Unexpected error! Please recheck the input/output data first. If the error appears again, contact adminstrator with your operating details please.";
            }
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            txtAttributes.Text = txtAttributes.Text.ToUpper();
            txtSeatType.Text = txtSeatType.Text.ToUpper();

            if (Session["ACL"].ToString().IndexOf("ND2") < 0)
            {
                lblErrAdd.Text = "Unauthorized!";
                return;
            }
            try
            {
                int.Parse(txtX.Text);
                int.Parse(txtY.Text);
                if (lstSpaceTypes.SelectedValue=="S")
                    int.Parse(txtRow.Text);
            }
            catch (Exception ex)
            {
                lblErrAdd.Text = "Seat's coordinate should be number!";
                return;
            }


            int ret_code;
            SqlCommand cmd = new SqlCommand();
            lblErrAdd.Text = "";
            try
            {
                cmd.CommandText = "bll_aircraft_add_seat_cell";
                SqlParameter para = cmd.Parameters.AddWithValue("@tail_no", lblTailNo.Text);
                para = cmd.Parameters.AddWithValue("@airline", Session["AIRLINE"].ToString());
                para = cmd.Parameters.AddWithValue("@x", txtX.Text);
                para = cmd.Parameters.AddWithValue("@y", txtY.Text);
                para = cmd.Parameters.AddWithValue("@cabin", lstAcCabins.SelectedValue);
                para = cmd.Parameters.AddWithValue("@cell_type", lstSpaceTypes.SelectedValue);
                para = cmd.Parameters.AddWithValue("@row", txtRow.Text);
                para = cmd.Parameters.AddWithValue("@col", lstCols.SelectedValue);
                para = cmd.Parameters.AddWithValue("@load_area", lstLoadArea.SelectedValue);
                para = cmd.Parameters.AddWithValue("@seat_type", txtSeatType.Text);
                para = cmd.Parameters.AddWithValue("@class", lstClasses.SelectedValue);
                para = cmd.Parameters.AddWithValue("@attributes", txtAttributes.Text);
                para = cmd.Parameters.AddWithValue("@user", Session["USER"].ToString());
                para = cmd.Parameters.AddWithValue("@ip_addr", Request.UserHostAddress.ToString());

                ret_code = TinyDAL.Exec(ref cmd);
                if (ret_code == 0)
                {
                    lblErrAdd.Text = "Done.";
                    //btnRefresh_Click(sender, e);
                    //return;
                }
                else if (ret_code == 1)
                    lblErrAdd.Text = "Inserting failed!";
                else if (ret_code == 2)
                    lblErrAdd.Text = "Invalid Row!";
                else if (ret_code == 3)
                    lblErrAdd.Text = "Invalid X or Y!";
                else if (ret_code == 4)
                    lblErrAdd.Text = "Row/Col existed!";
                else if (ret_code == 5)
                    lblErrAdd.Text = "Y exceeded 15!";
                else
                    lblErrAdd.Text = "Error:" + ret_code.ToString();

                lbtnQuery_Click(sender, e);
            }
            catch (Exception ex)
            {
                if (Application["DEBUG"].ToString() == "1")
                    lblErrAdd.Text = ex.Message;
                else
                    lblErrAdd.Text = "Unexpected error! Please recheck the input/output data first. If the error appears again, contact adminstrator with your operating details please.";
            }


        }
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            if (Session["ACL"].ToString().IndexOf("ND2") < 0)
            {
                lblError.Text = "Unauthorized!";
                return;
            }

            string[] strArray;
            string key;
            if (Request.Form["CELL"] == null)
            {
                lblError.Text = "Please select a record.";
                return;
            }
            key = Request.Form["CELL"];
            strArray = key.Split('|');

            int ret_code;

            SqlCommand cmd = new SqlCommand();
            lblError.Text = "";
            try
            {
                cmd.CommandText = "bll_aircraft_delete_seat_cell";
                SqlParameter para = cmd.Parameters.AddWithValue("@tail_no", lblTailNo.Text);
                para = cmd.Parameters.AddWithValue("@airline", Session["AIRLINE"].ToString());
                para = cmd.Parameters.AddWithValue("@x", strArray[0]);
                para = cmd.Parameters.AddWithValue("@y", strArray[1]);
                para = cmd.Parameters.AddWithValue("@user", Session["USER"].ToString());
                para = cmd.Parameters.AddWithValue("@ip_addr", Request.UserHostAddress.ToString());

                ret_code = TinyDAL.Exec(ref cmd);
                if (ret_code == 0)
                {
                    lblError.Text = "Done.";
                    lbtnQuery_Click(sender, e);
                    return;
                }
                else if (ret_code == 1)
                    lblError.Text = "Deleting failed!";
                else
                    lblError.Text = "Error:" + ret_code.ToString();
            }
            catch (Exception ex)
            {
                if (Application["DEBUG"].ToString() == "1")
                    lblError.Text = ex.Message;
                else
                    lblError.Text = "Unexpected error! Please recheck the input/output data first. If the error appears again, contact adminstrator with your operating details please.";
            }
        }
        protected void btnCopy_Click(object sender, EventArgs e)
        {
            if (Session["ACL"].ToString().IndexOf("ND2") < 0)
            {
                lblError.Text = "Unauthorized!";
                return;
            }

            int ret_code;
            SqlCommand cmd = new SqlCommand();
            lblError.Text = "";
            try
            {
                cmd.CommandText = "bll_aircraft_copy_seat_map";
                SqlParameter para = cmd.Parameters.AddWithValue("@tail_no", lblTailNo.Text);
                para = cmd.Parameters.AddWithValue("@new_tail_no", lstNewTailNos.SelectedValue);
                para = cmd.Parameters.AddWithValue("@user", Session["USER"].ToString());
                para = cmd.Parameters.AddWithValue("@airline", Session["AIRLINE"].ToString());
                para = cmd.Parameters.AddWithValue("@ip_addr", Request.UserHostAddress.ToString());

                ret_code = TinyDAL.Exec(ref cmd);
                if (ret_code == 0)
                {
                    lblError.Text = "Done.";
                    //btnRefresh_Click(sender, e);
                    return;
                }
                else if (ret_code == 1)
                    lblError.Text = "Aircraft Exist!";
                else if (ret_code == 2)
                    lblError.Text = "Diffrent Aircraft Type!";
                else if (ret_code == 3)
                    lblError.Text = "Seat map exist!";
                else if (ret_code == 4)
                    lblError.Text = "Copy failed!";
                else
                    lblError.Text = "Error:" + ret_code.ToString();
            }
            catch (Exception ex)
            {
                if (Application["DEBUG"].ToString() == "1")
                    lblError.Text = ex.Message;
                else
                    lblError.Text = "Unexpected error! Please recheck the input/output data first. If the error appears again, contact adminstrator with your operating details please.";
            }
        }
        protected void btnClear_Click(object sender, EventArgs e)
        {
            if (Session["ACL"].ToString().IndexOf("ND2") < 0)
            {
                lblErrCopy.Text = "Unauthorized!";
                return;
            }

            int ret_code;

            SqlCommand cmd = new SqlCommand();
            lblErrCopy.Text = "";
            try
            {
                cmd.CommandText = "bll_aircraft_clear_seat_map";
                SqlParameter para = cmd.Parameters.AddWithValue("@tail_no", lblTailNo.Text);
                para = cmd.Parameters.AddWithValue("@airline", Session["AIRLINE"].ToString());
                para = cmd.Parameters.AddWithValue("@user", Session["USER"].ToString());
                para = cmd.Parameters.AddWithValue("@ip_addr", Request.UserHostAddress.ToString());

                ret_code = TinyDAL.Exec(ref cmd);
                if (ret_code == 0)
                {
                    lblErrCopy.Text = "Done.";
                    lbtnQuery_Click(sender, e);
                    return;
                }
                else if (ret_code == 1)
                    lblErrCopy.Text = "Deleting failed!";
                else if (ret_code == 4)
                    lblErrCopy.Text = "Invalid aircraft!";
                else
                    lblErrCopy.Text = "Error:" + ret_code.ToString();
            }
            catch (Exception ex)
            {
                if (Application["DEBUG"].ToString() == "1")
                    lblError.Text = ex.Message;
                else
                    lblError.Text = "Unexpected error! Please recheck the input/output data first. If the error appears again, contact adminstrator with your operating details please.";
            }
        }
        protected void btnChange_Click(object sender, EventArgs e)
        {
            if (Session["ACL"].ToString().IndexOf("ND2") < 0)
            {
                lblErrChange.Text = "Unauthorized!";
                return;
            }
            if (lstEditTarget.SelectedValue == "S" || lstEditTarget.SelectedValue == "C")
            {
                if (txtNewValue.Text.Trim().Length > 2)
                {
                    lblErrChange.Text = "New value is too long!";
                    return;
                }
            }

            int ret_code;
            SqlCommand cmd = new SqlCommand();
            lblErrChange.Text = "";
            try
            {
                cmd.CommandText = "bll_aircraft_batch_set_seats_reserving";
                SqlParameter para = cmd.Parameters.AddWithValue("@tail_no", lblTailNo.Text);
                para = cmd.Parameters.AddWithValue("@user_airline", Session["AIRLINE"].ToString());
                para = cmd.Parameters.AddWithValue("@change_target", lstEditTarget.SelectedValue);
                para = cmd.Parameters.AddWithValue("@new_value", txtNewValue.Text.Trim());
                para = cmd.Parameters.AddWithValue("@where_clause", txtWhere.Text);
                para = cmd.Parameters.AddWithValue("@user", Session["USER"].ToString());
                para = cmd.Parameters.AddWithValue("@ip_addr", Request.UserHostAddress.ToString());

                ret_code = TinyDAL.Exec(ref cmd);
                if (ret_code == 0)
                {
                    lblErrChange.Text = "Done.";
                    //btnRefresh_Click(sender, e);
                    //return;
                }
                else if (ret_code == 1)
                    lblErrChange.Text = "Illegal verbs";
                else if (ret_code == 2)
                    lblErrChange.Text = "The aircraft is not belong to the airline!";
                else if (ret_code == 3)
                    lblErrChange.Text = "Invalid target!";
                else if (ret_code == 3)
                    lblErrChange.Text = "Updating failed!";
                else
                    lblErrChange.Text = "Error:" + ret_code.ToString();

                lbtnQuery_Click(sender, e);
            }
            catch (Exception ex)
            {
                if (Application["DEBUG"].ToString() == "1")
                    lblErrChange.Text = ex.Message;
                else
                    lblErrChange.Text = "Unexpected error! Please recheck the input/output data first. If the error appears again, contact adminstrator with your operating details please.";
            }
        }
        protected void lstClasses_DataBound(object sender, EventArgs e)
        {
            lstClasses.Items.Add(new ListItem("* - (No Control) ", "*"));
        }
    }
}